#include "ip_packet.h"
#include <iostream>
#include <fstream>
#include <cstring>

// 解封函数，从文件读取数据包并提取数据
std::string decapsulate(const std::string& filename) {
    // 从文件读取数据包
    std::ifstream inFile(filename, std::ios::binary);
    if (!inFile.is_open()) {
        std::cerr << "文件打开失败！" << std::endl;
        return "";
    }

    // 获取文件大小
    inFile.seekg(0, std::ios::end);
    size_t fileSize = inFile.tellg();
    inFile.seekg(0, std::ios::beg);

    // 读取数据包
    unsigned char packet[fileSize];
    inFile.read(reinterpret_cast<char*>(packet), fileSize);
    inFile.close();

    // 提取IPv4头部
    IPv4Header header;
    memcpy(&header, packet, sizeof(IPv4Header));

    // 校验和验证
    if  (calculateChecksum((unsigned short*)&header, sizeof(IPv4Header))!=0) {
        std::cerr << "校验和错误！" << std::endl;
        return "";
    }

    // 提取数据部分
    std::string data(reinterpret_cast<char*>(packet + sizeof(IPv4Header)), fileSize - sizeof(IPv4Header));
    return data;
}

int main() {
    // 调用解封函数，从 "ip_packet.dat" 文件中解封数据
    std::string data = decapsulate("ip_packet.dat");
    if (!data.empty()) {
        std::cout << "解封后的数据: " << data << std::endl;
    }

    return 0;
}
